#include<stdio.h>
#include<string.h>
#include<stdbool.h>

int rs232c_encode(double *volts,int volts_size,const char *msg,int size)//RS232C coding function
{
    if(volts==NULL||msg==NULL||size<=0||volts_size<size*10) return -1;//Parameter error
    int index=0;//Index of the array volts
    for(int i=0;i<size;i++)
	{
        char c=msg[i];
        volts[index++] = -12.0;//Idle bit (logical 1, negative voltage)
        volts[index++] = +12.0;//Start bit (logical 0, positive voltage)
        //Data bit (7-bit)
        for(int j=0;j<7;j++)
		{
            bool bit=(c>>j) & 0x01;//Starting from the lowest bit
            volts[index++]=bit? -12.0 : +12.0; //Logical 1 is negative voltage, logical 0 is positive voltage
        }
        volts[index++]= -12.0;//Idle bit (logical 1, negative voltage)
    }
    return index;//Return the length of the sequence of generated voltage values
}

int rs232c_decode(char *msg,int size,const double *volts,int volts_size)//RS232C decoding function
{
    if(msg==NULL||volts==NULL||size<=0||volts_size<10) return -1;//Parameter error
    int index=0;//Index of the array volts
    int msg_index=0;//Index of the array msg
    while(index<volts_size&&msg_index<size)
	{
        if(volts[index]<0)//finding start bit (logical 0, positive voltage)
		{
            index++;//Skip idle bit
            continue;
        }
        index++;//Detected start bit
        //Read data bits (7-bit)
        char c=0;
        for(int j=0;j<7;j++)
		{
            if(index>=volts_size) return -1;//Insufficient data
            bool bit=(volts[index++]>0)?0:1;//Negetive voltage is logical 1, positive voltage is logical 0
            c|=(bit<<j);//Combine from the lowest bit
        }
        msg[msg_index++]=c;//Store the decoded characters
        index++;//Skip the stop bit (logical 1)
    }
    return msg_index;//Return the number of decoded characters 
}

int main()
{
    const char *msg="A";//Input the characters
    double volts[100];//Store the voltage value sequence
    char decoded_msg[10];//Store the decoded characters
    int volts_size=rs232c_encode(volts,100,msg,1);//coding
    if(volts_size<0)
	{
        printf("Compilation failed!\n");
        return -1;
    }
    printf("Voltage value sequence:\n");//print the voltage value sequence
    for(int i=0;i<volts_size;i++)
	{
        printf("%.1f ", volts[i]);
    }
    printf("\n");
    int decoded_size=rs232c_decode(decoded_msg,10,volts,volts_size);//decoding
    if(decoded_size<0)
	{
        printf("Decoding failed!\n");
        return -1;
    }//print the decoding result
    printf("Decoding result:");
    for(int i=0;i<10;i++)
    {
        printf("%c",decoded_msg[i]);
    }
    printf("\n");
    return 0;
}